// import React from 'react'
import { Link, useNavigate } from "react-router-dom";
import { Button, Form, Input, Toast } from "antd-mobile";
import Logo from "../components/Logo";
import MyNavBar from "../components/nav-bar";
import { userRegAPI } from "../services/auth";
import { setToken } from "../utils/tools";

function Reg() {
  const navigate = useNavigate();

  const onFinish = async (v) => {
    const { rPassword, ...other } = v;
    if (rPassword == v.password) {
      const res = await userRegAPI(other);
      if (res.success) {
        setToken(res.data);
        navigate("/user", { replace: true });
        Toast.show({ icon: "success", content: "注册成功" });
        return;
      }
      Toast.show({ icon: "fail", content: "注册失败" });
      return;
    }
    Toast.show({ icon: "fail", content: "两次密码输入不一致" });
  };

  return (
    <div>
      <MyNavBar title="注册界面" />
      <Logo />
      <Form
        onFinish={onFinish}
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Header>用户登录</Form.Header>
        <Form.Item
          label="用户名"
          name="userName"
          rules={[{ required: true, message: "请输入用户名" }]}
        >
          <Input placeholder="请输入用户名" clearable></Input>
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input type="password" placeholder="请输入密码" clearable></Input>
        </Form.Item>
        <Form.Item
          label="再次输入密码"
          name="rPassword"
          rules={[{ required: true, message: "请重新输入密码" }]}
        >
          <Input type="password" placeholder="请重新输入密码" clearable></Input>
        </Form.Item>
        <Form.Item label="昵称" name="nickName">
          <Input placeholder="请输入昵称 (选填)" clearable></Input>
        </Form.Item>
        <Form.Item label="地址" name="address">
          <Input placeholder="请输入地址 (选填)" clearable></Input>
        </Form.Item>
        <Form.Item label="联系方式" name="mobile">
          <Input placeholder="请输入联系方式 (选填)" clearable></Input>
        </Form.Item>
      </Form>
      <div
        style={{
          paddingRight: "13px",
          display: "flex",
          justifyContent: "flex-end",
        }}
      >
        <Link to="/login">已有账号，我要注册</Link>
      </div>
    </div>
  );
}

export default Reg;
